<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="智能体名称	" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入智能体名称	"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="状态" prop="isActive">
        <el-select
          v-model="queryParams.isActive"
          placeholder="请选择状态"
          clearable
          style="width: 200px"
        >
          <el-option label="正常" :value="0" />
          <el-option label="禁用" :value="1" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['admin:menu:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="roleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="智能体ID" prop="id" width="200" />
      <el-table-column
        label="智能体名称"
        prop="name"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="智能体类型" align="center" prop="agentType">
            <template #default="scope">
              <span>
                {{scope.row.agentType === 0? "老师AI": scope.row.agentType === 1? "AI虚拟人物": scope.row.agentType === 2? "智能体": scope.row.agentType === 3? "小看": "未知"}}
              </span>
            </template>
          </el-table-column>
      <el-table-column label="注释" prop="note" width="120" />

      <el-table-column label="价格" prop="price" width="120" />
      <el-table-column label="二级分类" prop="category" width="120" />
      <el-table-column label="封面URL" prop="agentUrl" width="400" />
      <el-table-column label="注释" prop="note" width="120" />
      <el-table-column
        label="是否禁用"
        align="center"
        width="100"
        v-hasPermi="['admin:role:active']"
      >
        <template #default="scope">
          <el-switch
            v-model="scope.row.isActive"
            :active-value="0"
            :inactive-value="1"
            @change="(val) => handleStatusChange(scope.row, val)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" prop="sort" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip
            content="修改"
            placement="top"
            v-if="scope.row.isAdmin !== 1"
          >
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['admin:role:update']"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            content="删除"
            placement="top"
            v-if="scope.row.isAdmin !== 1"
          >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['admin:user:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="二级分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择模式">
                <el-option label="0" :value="0"></el-option>
                <el-option label="1" :value="1"></el-option>
                <el-option label="2" :value="2"></el-option>
                <el-option label="3" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="智能体类型" prop="agentType">
              <el-select v-model="form.agentType" placeholder="请选择模式">
                <el-option label="0" :value="0"></el-option>
                <el-option label="1" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="智能体名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入智能体名称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="form.sort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-col :span="24">
          <el-form-item label="注释" prop="note">
            <el-input
              v-model="form.note"
              type="textarea"
              placeholder="请输入注释"
              maxlength="200"
            />
          </el-form-item>
        </el-col>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import {
  listRole,
  agentadd,
  agentupdate,
  agentInfo,activeID,deleteRemove
} from "@/api/min-app/agent";
const { proxy } = getCurrentInstance();

const roleList = ref([]);
const loading = ref(true);
const total = ref(0);
const dateRange = ref([]);
const open = ref(false);
const title = ref("");
const showSearch = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    page: 1,
    size: 10,
    name: '',
    isActive: '',
  },
});

const { queryParams, form, rules } = toRefs(data);
import { ElMessage, ElMessageBox } from "element-plus";

/** 查询角色列表 */
function getList() {
  loading.value = true;

  const params = {
    page: queryParams.value.page,
    size: queryParams.value.size,
    name: queryParams.value.name || "",
    isActive: queryParams.value.isActive || '-1',
  };

  listRole(params).then((res) => {
    roleList.value = res.data.records;
    total.value = Number(res.data.total); // 保证是数字
    loading.value = false;
  });
}

/** 重置表单 */
function reset() {
  form.value = {
    agentType: 0,
    category: 0,
    name: "",
    isActive: "",
    sort: 0,
  };
  proxy.resetForm("menuRef");
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.roleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  agentInfo(row.id).then((response) => {
    const { allDept, allRole, belongToDept, belongToRole, ...userInfo } = response.data;
        Object.assign(form.value, userInfo);
      
    open.value = true;
    title.value = "修改用户";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["menuRef"].validate((valid) => {
    if (valid) {
      const payload = {
        ...form.value,
        agentType: Number(form.value.agentType) || 0,
        name: form.value.name || "",
        note: form.value.note || "",
        sort: Number(form.value.sort) || 0,
        category: Number(form.value.category) || 0,
      };
      if (form.value.id) {
        agentupdate(payload).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        agentadd(payload).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

//是否禁用
function handleStatusChange(row) {
  const text = row.isActive === 0 ? "启用" : "禁用";

  proxy.$modal
    .confirm(`确认要${text} "${row.name}" 用户吗?`)
    .then(() => activeID(row.id, row.isActive))
    .then(() => {
      proxy.$modal.msgSuccess(`${text}成功`);
    })
    .catch(() => {
      // 接口失败时回滚
      row.isActive = row.isActive === 0 ? 1 : 0;
    });
}

// 删除
function handleDelete(row) {
  ElMessageBox.confirm("确认删除该智能体吗？", "提示", { type: "warning" })
    .then(async () => {
      const res = await deleteRemove(row.id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    })
    .catch(() => {});
}

/** 搜索按钮 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

/** 重置按钮 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.page = 1;
  getList();
}

getList();
</script>
